import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 模拟实现二叉树的操作
 */
public class MyBinaryTree {

    public static class TreeNode {
        public char val;
        public TreeNode left;//左孩子的引用
        public TreeNode right;//右孩子的引用

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public static int nodeSize;


    /**
     * 创建一棵二叉树 返回这棵树的根节点
     *
     * @return
     */
    public TreeNode createTree() {
        TreeNode root = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        root.left = B;
        root.right = C;
        B.left = D;
        B.right = G;
        C.left = E;
        C.right = F;
        /*E.left = G;*/
        return root;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        preOrder(root.left);
        System.out.print(root.val + " ");
        preOrder(root.right);
    }

    // 后序遍历
    void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        preOrder(root.left);
        preOrder(root.right);
        System.out.print(root.val + " ");
    }

    /**
     * 后序非递归遍历版本一
     */
    public List<Character> postorderTraversal1(TreeNode root) {
        List<Character> list = new LinkedList<>();
        if(root == null) {
            return list;
        }
        //创建一个栈
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode previousNode = root;
        while(!stack.empty()) {
            TreeNode cur = stack.peek();
            if((cur.left == null && cur.right == null)
                    || previousNode == cur.right
                    || (previousNode == cur.left && cur.right == null)) {
                list.add(cur.val);
                previousNode = cur;
                stack.pop();
                continue;
            }
            if(cur.left != null && cur.left != previousNode) {
                stack.push(cur.left);
                continue;
            }
            if(cur.right != null) {
                stack.push(cur.right);
            }
        }
        return list;
    }

    /**
     * 后序非递归遍历版本二
     */
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode previousNode = root;
        while(cur != null || !stack.empty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || previousNode == top.right) {
                list.add(top.val);
                previousNode = top;
                stack.pop();
            }else {
                cur = top.right;
            }
        }
        return list;
    }

    /**
     * 中序非递归遍历
     */
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> list = new LinkedList<>();
        //创建一个栈
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.empty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        return list;
    }

    /**
     * 前序非递归遍历
     */
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        //cur != null不仅是为了防止root == null造成的空指针异常
        //更是因为当根节点的左子树完全走完时，根节点出栈，此时栈已经为空
        //但是不确定根节点的右子树是否为null（存储在cur中），就会导致漏算
        while(cur != null || !stack.empty()) {
            while(cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }

    /**
     * 获取树中节点的个数：遍历思路
     */
    void size(TreeNode root) {
        if(root == null) {
            return;
        }
        nodeSize++;
        preOrder(root.left);
        preOrder(root.right);
    }

    /**
     * 获取节点的个数：子问题的思路
     *
     * @param root
     * @return
     */
    int size2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return size2(root.left) + size2(root.right) + 1;
    }


    /**
     *获取叶子节点的个数：遍历思路
     */
    public static int leafSize = 0;

    void getLeafNodeCount1(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            nodeSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    /*
     获取叶子节点的个数：子问题
     */
    int getLeafNodeCount2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) +
                getLeafNodeCount2(root.right);
    }

    /*
    获取第K层节点的个数
     */
    int getKLevelNodeCount(TreeNode root, int k) {
        if(root == null || k < 1) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k - 1) +
                getKLevelNodeCount(root.right,k - 1);
    }

    /*
     获取二叉树的高度
     时间复杂度：O(N)
     */
    int getHeight(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = getHeight(root.left);
        int right = getHeight(root.right);
        return Math.max(left, right) + 1;
    }


    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val) {
        if(root == null) {
           return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode ret = find(root.left,val);
        if(ret != null) {
            return ret;
        }
        ret = find(root.right,val);
        if(ret != null) {
            return ret;
        }
        return null;
    }

    //层序遍历
    void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    //层序遍历并实现分层
    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> list = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null) {
            return list;
        }
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for(int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                level.add((int) cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            list.add(level);
        }
        return list;
    }

    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return false;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                return false;
            }
        }
        return true;
    }

    //判断是否是平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if(getDepth(root) == -1) {
            return false;
        }
        return true;
    }

    //将求树的高度的方法稍微修改，加入了判断两棵树高度是否相差不大于1的代码
    public int getDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int left = getDepth(root.left);
        int right = getDepth(root.right);
        if(left == -1 || right == -1) {
            return -1;
        }
        int x = Math.abs(left - right);
        if(x > 1) {
            return -1;
        }
        return Math.max(left, right) + 1;
    }

    //判断一棵树是否是另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {

        //1、判断两棵树 是不是两颗相同的树
        if(isSameTree(root,subRoot)) {
            return true;
        }

        if(root == null) {
            return false;
        }

        //2、subRoot是不是 root.left 子树
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        //3、subRoot是不是 root.right 子树
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }

    //判断两棵树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if((p == null && q != null)  || (p != null && q == null) ) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    //判断是否为对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }

        return isSymmetricTree(root.left,root.right);
    }

    public boolean isSymmetricTree(TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null) {
            return true;
        }
        if(root1 == null || root2 == null) {
            return false;
        }
        if(root1.val != root2.val) {
            return false;
        }
        return isSymmetricTree(root1.left,root2.right) &&
                isSymmetricTree(root1.right,root2.left);
    }

    //翻转二叉树
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public static Stack<TreeNode> stack1 = new Stack();
    public static Stack<TreeNode> stack2 = new Stack();

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        getRoute(root,p,stack1);
        getRoute(root,q,stack2);
        int size1 = stack1.size();
        int size2 = stack2.size();
        if(size1 > size2) {
            while(size1 > size2) {
                stack1.pop();
                size1--;
            }
        } else {
            while(size2 > size1) {
                stack2.pop();
                size2--;
            }
        }
        while(!stack1.empty()) {
            TreeNode cur1 = stack1.pop();
            TreeNode cur2 = stack2.pop();
            if(cur1.val == cur2.val) {
                return cur1;
            }
        }
        return null;
    }

    //找到两个节点的最近公共节点
    public TreeNode getRoute(TreeNode root,TreeNode torget,Stack<TreeNode> stack) {
        if(root == null) {
            return null;
        }
        stack.push(root);
        if(root.val == torget.val) {
            return root;
        }
        TreeNode cur = getRoute(root.left,torget,stack);
        if(cur != null) {
            return cur;
        }
        cur = getRoute(root.right,torget,stack);
        if(cur != null) {
            return cur;
        }
        stack.pop();
        return null;
    }

    //从下到上从左到右分层遍历
    //由于该方法的类类型是 Integer ，因此与 char 类型的成员变量并不适配
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null) {
            return list;
        }
        queue.offer(root);
        while(!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                level.add((int) cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            list.add(0,level);
        }
        return list;
    }

    /**
     * 利用中序和后序遍历二叉树
     */
    /*public static int mid;*/
    public TreeNode buildTree(char[] inorder, char[] postorder) {
        if(postorder.length == 0) {
            return null;
        }
        mid = postorder.length - 1;
        return buildTreeWay(inorder,postorder,0,inorder.length - 1);
    }

    //构建二叉树
    public TreeNode buildTreeWay(char[] inorder,char[] postorder,int start,int end) {
        if(start > end) {
            return null;
        }
        for(int i = start; i <= end; i++) {
            if(inorder[i] == postorder[mid]) {
                TreeNode root = new TreeNode(inorder[i]);
                mid--;
                root.right = buildTreeWay(inorder,postorder,i + 1,end);
                root.left = buildTreeWay(inorder,postorder,start,i - 1);
                return root;
            }
        }
        return null;
    }

    /**
     * 利用前序和中序遍历二叉树
     */
    public static int mid = 0;
    public TreeNode buildTree2(char[] preorder, char[] inorder) {
        if(preorder.length == 0) {
            return null;
        }
        return buildTreeWay2(preorder,inorder,0,inorder.length - 1);
    }

    //构建二叉树
    public TreeNode buildTreeWay2(char[] preorder,char[] inorder,int start,int end) {
        if(start > end) {
            return null;
        }
        for(int i = start; i <= end; i++) {
            if(inorder[i] == preorder[mid]) {
                TreeNode root = new TreeNode(inorder[i]);
                mid++;
                root.left = buildTreeWay2(preorder,inorder,start,i - 1);
                root.right = buildTreeWay2(preorder,inorder,i + 1,end);
                return root;
            }
        }
        return null;
    }
}
